<template>
  <div class="add-payment-container">
    <div class="form-container">
      <h2 class="form-title">
        {{ isViewMode ? '查看付款管理' : (isEditMode ? '编辑付款管理' : '添加付款管理') }}
      </h2>
      
      <form @submit.prevent="handleSubmit" class="payment-form">
        <!-- 标题 -->
        <div class="form-group">
          <label class="required">标题</label>
          <input 
            v-model="formData.title" 
            type="text" 
            placeholder="请输入标题"
            class="form-input"
            :readonly="isViewMode"
            required
          />
        </div>

        <!-- 用途描述 -->
        <div class="form-group">
          <label class="required">用途描述</label>
          <textarea 
            v-model="formData.usageDescription" 
            placeholder="请输入用途描述"
            class="form-textarea"
            rows="4"
            :readonly="isViewMode"
            required
          ></textarea>
        </div>

        <!-- 付款金额 -->
        <div class="form-group">
          <label class="required">付款金额</label>
          <input 
            v-model="formData.paymentAmount" 
            type="number" 
            placeholder="请输入付款金额"
            class="form-input"
            :readonly="isViewMode"
            required
          />
        </div>

        <!-- 支付方式 -->
        <div class="form-group">
          <label class="required">支付方式</label>
          <div class="radio-group">
            <label v-for="method in paymentMethods" :key="method.value" class="radio-item">
              <input 
                v-model="formData.paymentMethod" 
                type="radio" 
                :value="method.value"
                class="radio-input"
                :disabled="isViewMode"
                required
              />
              <span class="radio-label">{{ method.label }}</span>
            </label>
            <div v-if="formData.paymentMethod === 'other'" class="other-input">
              <input 
                v-model="formData.otherMethod" 
                type="text" 
                placeholder="请输入其他支付方式"
                class="form-input"
                :readonly="isViewMode"
              />
            </div>
          </div>
        </div>

        <!-- 支付对象 -->
        <div class="form-group">
          <label class="required">支付对象</label>
          <input 
            v-model="formData.payee" 
            type="text" 
            placeholder="请输入支付对象"
            class="form-input"
            :readonly="isViewMode"
            required
          />
        </div>

        <!-- 开户行 -->
        <div class="form-group">
          <label class="required">开户行</label>
          <input 
            v-model="formData.issuingBank" 
            type="text" 
            placeholder="请输入开户行"
            class="form-input"
            :readonly="isViewMode"
            required
          />
        </div>

        <!-- 银行账户 -->
        <div class="form-group">
          <label class="required">银行账户</label>
          <input 
            v-model="formData.bankofDeposit" 
            type="text" 
            placeholder="请输入银行账户"
            class="form-input"
            :readonly="isViewMode"
            required
          />
        </div>

        <!-- 申请人 -->
        <div class="form-group">
          <label class="required">申请人</label>
          <input 
            v-model="formData.requester" 
            type="text" 
            placeholder="请输入申请人"
            class="form-input"
            :readonly="isViewMode"
            required
          />
        </div>

        <!-- 付款日期 -->
        <div class="form-group">
          <label class="required">付款日期</label>
          <input 
            v-model="formData.paymentDate" 
            type="datetime-local" 
            placeholder="请选择付款日期"
            class="form-input"
            :readonly="isViewMode"
            required
          />
        </div>

        <!-- 备注 -->
        <div class="form-group">
          <label>备注</label>
          <textarea 
            v-model="formData.notes" 
            placeholder="请输入备注"
            class="form-textarea"
            rows="3"
            :readonly="isViewMode"
          ></textarea>
        </div>

        <!-- 发票附件 -->
        <div class="form-group">
          <label>发票附件</label>
          <div class="upload-area" @click="!isViewMode && triggerFileUpload()">
            <input 
              ref="fileInput"
              type="file" 
              @change="handleFileUpload"
              accept="image/*"
              style="display: none"
              :disabled="isViewMode"
            />
            <div v-if="!uploadedImageUrl && !existingImageUrl" class="upload-content">
              <div class="upload-icon">+</div>
              <div class="upload-text">{{ isViewMode ? '暂无图片' : '上传图片' }}</div>
            </div>
            <div v-else class="uploaded-image">
              <img :src="displayImageUrl" alt="已上传的图片" class="preview-image" />
              <div v-if="!isViewMode" class="image-actions">
                <button type="button" @click="removeImage" class="btn-remove">删除</button>
                <button type="button" @click="triggerFileUpload" class="btn-change">更换</button>
              </div>
            </div>
          </div>
          <div v-if="uploading" class="upload-progress">
            <div class="progress-text">上传中... {{ uploadProgress }}%</div>
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
            </div>
          </div>
        </div>

        <!-- 按钮组 -->
        <div class="button-group">
          <button 
            v-if="!isViewMode" 
            type="submit" 
            class="btn btn-primary" 
            :disabled="loading"
          >
            {{ loading ? '提交中...' : (isEditMode ? '更新' : '提交') }}
          </button>
          <button 
            v-if="!isViewMode" 
            type="button" 
            @click="handleCancel" 
            class="btn btn-secondary"
          >
            取消
          </button>
          <button 
            v-if="!isViewMode" 
            type="button" 
            @click="handleSaveDraft" 
            class="btn btn-draft"
          >
            保存草稿
          </button>
          <button 
            v-if="isViewMode" 
            type="button" 
            @click="handleBack" 
            class="btn btn-primary"
          >
            返回
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { paymentApi } from '@/api'

const router = useRouter()
const route = useRoute()

// 判断模式
const isEditMode = computed(() => route.query.mode === 'edit')
const isViewMode = computed(() => route.query.mode === 'view')
const editId = computed(() => route.query.id as string)

// 表单数据 - 根据API文档字段
const formData = reactive({
  id: 0,
  title: '',
  usageDescription: '',
  paymentAmount: 0,
  paymentMethod: 'wechat',
  otherMethod: '',
  payee: '',
  issuingBank: '',
  bankofDeposit: '',
  requester: '',
  paymentDate: '',
  notes: '',
  invoiceAttachment: '',
  createdTime: '',
  processDetailCode: '',
  approvalTypeCode: ''  // 添加审批类型代码字段
})

// 支付方式选项
const paymentMethods = [
  { value: 'wechat', label: '微信支付' },
  { value: 'alipay', label: '支付宝支付' },
  { value: 'unionpay', label: '银联支付' },
  { value: 'corporate', label: '企业转账' },
  { value: 'offline', label: '线下支付' },
  { value: 'other', label: '其它' }
]

// 文件输入引用
const fileInput = ref<HTMLInputElement>()
const loading = ref(false)
const uploading = ref(false)
const uploadProgress = ref(0)
const uploadedImageUrl = ref('')
const existingImageUrl = ref('') // 存储现有图片URL

// 计算显示的图片URL
const displayImageUrl = computed(() => {
  return uploadedImageUrl.value || existingImageUrl.value
})

// 获取付款详情数据
const fetchPaymentDetails = async (id: string) => {
  try {
    loading.value = true
    const response = await paymentApi.getPaymentDetail(parseInt(id))

    if (response.code === 200 && response.data) {
      const data = response.data
      console.log('详情响应:', response)
        
        // 填充表单数据
        formData.id = data.id || 0
        formData.title = data.title || ''
        formData.usageDescription = data.usageDescription || ''
        formData.paymentAmount = data.paymentAmount || 0
        formData.paymentMethod = data.paymentMethod || 'wechat'
        formData.otherMethod = data.paymentMethod === 'other' ? data.paymentMethod : ''
        formData.payee = data.payee || ''
        formData.issuingBank = data.issuingBank || ''
        formData.bankofDeposit = data.bankofDeposit || ''
        formData.requester = data.requester || ''
        formData.notes = data.notes || ''
        formData.invoiceAttachment = data.invoiceAttachment || ''
        formData.processDetailCode = data.processDetailCode || ''
        formData.createdTime = data.createdTime || ''
        formData.approvalTypeCode = data.approvalTypeCode || 'T006'  // 处理审批类型代码
        
        // 处理付款日期
        if (data.paymentDate) {
          const date = new Date(data.paymentDate)
          formData.paymentDate = date.toISOString().slice(0, 16)
        }
        
        // 处理现有图片
        if (data.invoiceAttachment && data.invoiceAttachment !== 'string') {
          existingImageUrl.value = data.invoiceAttachment
        }
        
        console.log('表单数据已填充:', formData)
      } else {
        alert(`获取详情失败：${response.message || '未知错误'}`)
      }
  } catch (error) {
    console.error('获取详情失败:', error)
    alert('获取详情失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 触发文件上传
const triggerFileUpload = () => {
  if (!isViewMode.value) {
    fileInput.value?.click()
  }
}

// 处理文件上传
const handleFileUpload = async (event: Event) => {
  if (isViewMode.value) return
  
  const target = event.target as HTMLInputElement
  if (target.files && target.files[0]) {
    const file = target.files[0]
    
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      alert('请选择图片文件')
      return
    }
    
    // 验证文件大小 (限制为5MB)
    const maxSize = 5 * 1024 * 1024
    if (file.size > maxSize) {
      alert('图片大小不能超过5MB')
      return
    }
    
    try {
      await uploadImageToQiniu(file)
    } catch (error) {
      console.error('上传失败:', error)
      alert('图片上传失败，请重试')
    }
  }
}

// 上传图片到七牛云
const uploadImageToQiniu = async (file: File) => {
  uploading.value = true
  uploadProgress.value = 0
  
  try {
    const uploadFormData = new FormData()
    uploadFormData.append('file', file)
    
    // 模拟上传进度
    const progressInterval = setInterval(() => {
      if (uploadProgress.value < 90) {
        uploadProgress.value += Math.random() * 10
      }
    }, 200)
    
    const response = await paymentApi.uploadImage(file)
    
    clearInterval(progressInterval)
    uploadProgress.value = 100
    
    if (response.code === 200 && response.data && response.data.success) {
      // 保存返回的图片URL
      uploadedImageUrl.value = response.data.fileUrl
      formData.invoiceAttachment = response.data.fileUrl
      console.log('图片上传成功，URL:', response.data.fileUrl)
    } else {
      throw new Error(response.message || '上传失败')
    }
  } catch (error) {
    console.error('上传图片失败:', error)
    throw error
  } finally {
    uploading.value = false
    uploadProgress.value = 0
  }
}

// 删除图片
const removeImage = () => {
  if (isViewMode.value) return
  
  uploadedImageUrl.value = ''
  existingImageUrl.value = ''
  formData.invoiceAttachment = ''
  // 清空文件输入
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 提交表单
const handleSubmit = async () => {
  if (loading.value || isViewMode.value) return
  
  loading.value = true
  
  try {
    // 准备提交数据 - 根据API文档结构
    const submitData = {
      id: formData.id,
      title: formData.title,
      usageDescription: formData.usageDescription,
      paymentAmount: Number(formData.paymentAmount),
      paymentMethod: formData.paymentMethod === 'other' ? formData.otherMethod : formData.paymentMethod,
      payee: formData.payee,
      issuingBank: formData.issuingBank,
      bankofDeposit: formData.bankofDeposit,
      requester: formData.requester,
      paymentDate: formData.paymentDate ? new Date(formData.paymentDate).toISOString() : new Date().toISOString(),
      notes: formData.notes,
      invoiceAttachment: formData.invoiceAttachment,
      createdTime: formData.createdTime || new Date().toISOString(),
      processDetailCode: formData.processDetailCode || '',
      approvalTypeCode: formData.approvalTypeCode  // 添加审批类型代码
    }

    console.log('提交数据:', submitData)

    // 根据模式选择不同的API
    const response = isEditMode.value 
      ? await paymentApi.updatePaymentManagemen(submitData)
      : await paymentApi.addPaymentManagemen(submitData)

    console.log('API响应:', response)
    
    if (response.code === 200) {
      alert(isEditMode.value ? '更新成功！' : '添加成功！')
      // 跳转到付款管理列表页面
      router.push('/PayMent')
    } else {
      alert(`${isEditMode.value ? '更新' : '添加'}失败：${response.message || '未知错误'}`)
    }
  } catch (error) {
    console.error('提交失败:', error)
    alert('提交失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  formData.id = 0
  formData.title = ''
  formData.usageDescription = ''
  formData.paymentAmount = 0
  formData.paymentMethod = 'wechat'
  formData.otherMethod = ''
  formData.payee = ''
  formData.issuingBank = ''
  formData.bankofDeposit = ''
  formData.requester = ''
  formData.paymentDate = ''
  formData.notes = ''
  formData.invoiceAttachment = ''
  formData.processDetailCode = ''
  formData.createdTime = ''
  formData.approvalTypeCode = 'T006'  // 重置审批类型代码
  uploadedImageUrl.value = ''
  existingImageUrl.value = ''
}

// 取消操作
const handleCancel = () => {
  if (confirm('确定要取消吗？未保存的数据将丢失。')) {
    resetForm()
    // 跳转到付款管理列表页面
    router.push('/PayMent')
  }
}

// 返回操作
const handleBack = () => {
  router.push('/PayMent')
}

// 保存草稿
const handleSaveDraft = () => {
  console.log('保存草稿:', formData)
  // 这里可以调用保存草稿的API
  alert('草稿保存成功！')
}

// 组件挂载时加载数据
onMounted(() => {
  if ((isEditMode.value || isViewMode.value) && editId.value) {
    fetchPaymentDetails(editId.value)
  }
})
</script>

<style scoped>
.add-payment-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.form-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
  font-weight: bold;
}

.payment-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  font-weight: bold;
  color: #333;
  font-size: 14px;
}

.required::after {
  content: ' *';
  color: red;
}

.form-input, .form-textarea {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
}

.radio-input {
  margin: 0;
}

.radio-label {
  font-weight: normal;
  cursor: pointer;
}

.other-input {
  margin-top: 10px;
  width: 100%;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  min-height: 250px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
  position: relative;
  overflow: hidden;
}

.upload-area:hover {
  border-color: #007bff;
  background: #f0f8ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 123, 255, 0.15);
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  z-index: 1;
}

.upload-icon {
  font-size: 64px;
  color: #007bff;
  font-weight: 300;
  opacity: 0.8;
  transition: all 0.3s ease;
}

.upload-area:hover .upload-icon {
  transform: scale(1.1);
  opacity: 1;
}

.upload-text {
  color: #666;
  font-size: 16px;
  font-weight: 500;
  transition: color 0.3s ease;
}

.upload-area:hover .upload-text {
  color: #007bff;
}

.uploaded-image {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  width: 100%;
}

.preview-image {
  max-width: 400px;
  max-height: 300px;
  min-width: 300px;
  min-height: 220px;
  border-radius: 8px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  object-fit: cover;
  transition: all 0.3s ease;
  border: 3px solid #fff;
}

.preview-image:hover {
  transform: scale(1.02);
  box-shadow: 0 12px 35px rgba(0, 0, 0, 0.2);
}

.image-actions {
  display: flex;
  gap: 12px;
  margin-top: 10px;
}

.btn-remove, .btn-change {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  min-width: 80px;
  justify-content: center;
}

.btn-remove {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}

.btn-remove:hover {
  background: linear-gradient(135deg, #ff5252, #e53e3e);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.4);
}

.btn-change {
  background: linear-gradient(135deg, #007bff, #0056b3);
  color: white;
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.3);
}

.btn-change:hover {
  background: linear-gradient(135deg, #0056b3, #004085);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 123, 255, 0.4);
}

.upload-progress {
  margin-top: 15px;
  width: 100%;
  background: rgba(255, 255, 255, 0.9);
  padding: 15px;
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

.progress-text {
  text-align: center;
  color: #007bff;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #e9ecef;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #007bff, #00d4ff);
  transition: width 0.3s ease;
  position: relative;
}

.progress-fill::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  animation: shimmer 1.5s infinite;
}

@keyframes shimmer {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.button-group {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 30px;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  transition: all 0.3s;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #0056b3;
}

.btn-secondary {
  background: white;
  color: #007bff;
  border: 1px solid #007bff;
}

.btn-secondary:hover {
  background: #f8f9fa;
}

.btn-draft {
  background: #28a745;
  color: white;
}

.btn-draft:hover {
  background: #1e7e34;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-payment-container {
    padding: 10px;
  }
  
  .form-container {
    padding: 20px;
  }
  
  .radio-group {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .button-group {
    flex-direction: column;
  }

  .upload-area {
    min-height: 200px;
    padding: 15px;
  }
  
  .preview-image {
    max-width: 100%;
    min-width: 250px;
    min-height: 180px;
  }
  
  .image-actions {
    flex-direction: column;
    gap: 8px;
    width: 100%;
  }
  
  .btn-remove, .btn-change {
    width: 100%;
    padding: 10px;
  }
  
  .upload-icon {
    font-size: 48px;
  }
}

/* 查看模式样式 */
.form-input[readonly], 
.form-textarea[readonly] {
  background-color: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
}

.radio-input:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.upload-area[style*="cursor: not-allowed"] {
  cursor: not-allowed;
  opacity: 0.6;
}

.upload-area[style*="cursor: not-allowed"]:hover {
  border-color: #ddd;
  background: #fafafa;
  transform: none;
  box-shadow: none;
}
</style>
